package com.hmdp.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;


@RestController
@RequestMapping("/blog")
public class BlogController {

    @Resource
    private IBlogService blogService;
    @Resource
    private IUserService userService;

    @Autowired
    private IFollowService followService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //发布探店笔记并推送给粉丝
    @PostMapping
    public Result saveBlog(@RequestBody Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        //保存探店笔记
        blogService.save(blog);

        //推送到粉丝邮箱(redis) 粉丝拉去动态从redis中取
        List<Follow> followList = followService.lambdaQuery().eq(Follow::getFollowUserId, user.getId()).list();
        for (Follow follow : followList) {
            stringRedisTemplate.opsForZSet().add(FEED_KEY + follow.getUserId(), blog.getId().toString(), System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    //根据博客id查询博客笔记
    @GetMapping("/{blogId}")
    public Result queryBlogById(@PathVariable("blogId") Long blogId) {
        return blogService.queryBlogById(blogId);
    }

    //根据博客id查询点赞过该博客的前五个用户
    @GetMapping("/likes/{id}")
    public Result queryUsersLikeById(@PathVariable Long id) {
        return blogService.queryUsersLikeById(id);
    }

    //根据博客id 点赞/取消点赞
    @PutMapping("/like/{id}")
    public Result likeOrCancel(@PathVariable Long id) {
        return blogService.likeOrCancel(id);
    }

    //根据用户id查询所有笔记
    @GetMapping("/of/user")
    public Result queryBlogByUserId(@RequestParam("id") Long id,@RequestParam("current") Long currentPage){

        Page<Blog> blogPage = blogService.lambdaQuery().eq(Blog::getUserId, id).page(new Page<>(currentPage, SystemConstants.MAX_PAGE_SIZE));

        return Result.ok(blogPage.getRecords());
    }

    @GetMapping("/of/me")
    public Result queryMyBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .eq("user_id", user.getId()).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    @GetMapping("/hot")
    public Result queryHotBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
        });
        return Result.ok(records);
    }

    //滚动分页 上次时间最小值作为查询的max min为0 offset为上一次时间最小值有几个相同的值需要跳过 查询的个数
    @GetMapping("/of/follow")
    public Result scroll(@RequestParam("lastId") Long lastMinTime,@RequestParam(value = "offset",defaultValue = "0") Long offset) {
        return blogService.scroll(lastMinTime, offset);
    }
}
